package spring.boot.kafka.component;

import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.kafka.support.KafkaHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

@Component
public class TestTopicReceiver {
    protected final Logger log = LoggerFactory.getLogger(this.getClass());
    /**
     * 自动提交  enable-auto-commit: true
     */
  /*  @KafkaListener(topics = "test")
    public void auto(@Payload String message) {
        log.info("KafkaReceiver test=====自动提交 {}",message);
    }*/
   /* @KafkaListener(topics = "test")
    public void auto(ConsumerRecord<?, ?> record) {
        log.info("消费成功--->主题:{} 分区:{} 消息内容:{} 位移量:{} 时间:{}",record.topic(),record.partition(),record.value(),record.offset(),record.timestamp());

    }*/

    /**
     * 手动提交
     * @param message
     * @param topic
     * @param partition
     * @param ack
     * @param consumer
     */
    @KafkaListener(topics = "test",containerFactory = "ackContainerFactory")
    public void manual(@Payload String message,
                       @Header(KafkaHeaders.RECEIVED_TOPIC) String topic,
                       @Header(KafkaHeaders.RECEIVED_PARTITION_ID) int partition,
                       Acknowledgment ack,
                       Consumer consumer) {
        log.info("KafkaReceiver test=====手动提交 topic={} partition={} message={}",topic,partition,message);
        // 提交
        //consumer.commitAsync();
        // ack手动提交
        ack.acknowledge();

    }

}
